#!/usr/bin/env python
#
# dumb script to update copyright notice in a py sourcefile
#
from __future__ import print_function
import argparse
import sys
import os


new_copyright = (
    "# SPDX-License-Identifier: Apache-2.0\n"
    "# Copyright Contributors to the Rez Project"
)

lines = []
NO_COPYRIGHT = "NO_COPYRIGHT"
OTHER_COPYRIGHT = "OTHER_COPYRIGHT"

# just removes some verbosity in workflow so user can more easily see problems
IN_WORKFLOW = (os.getenv("GITHUB_ACTIONS") == "true")


def find_existing_copyright():
    i_comment_start = None
    i_start = None

    for i, line in enumerate(lines):
        if line.startswith('#'):
            if i_comment_start is None:
                i_comment_start = i

            if "Copyright" in line:
                if "Rez" in line:
                    i_start = i_comment_start
                else:
                    return OTHER_COPYRIGHT
        else:
            i_comment_start = None

    if i_start is None:
        return NO_COPYRIGHT

    i_end = i_start

    while True:
        if (i_end + 1) >= len(lines):
            break

        if lines[i_end + 1].startswith('#'):
            i_end += 1
        else:
            break

    return (i_start, i_end)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("FILE")
    parser.add_argument("-s", "--strip-copyright", action="store_true")
    parser.add_argument("-o", "--overwrite-file", action="store_true")
    opts = parser.parse_args()

    with open(opts.FILE) as f:
        txt = f.read()
    lines = txt.rstrip().split('\n')

    result = find_existing_copyright()

    if result == OTHER_COPYRIGHT:
        if not IN_WORKFLOW:
            print("Other copyright, skipping %s" % opts.FILE, file=sys.stderr)
        sys.exit(1)

    # strip existing copyright
    if result != NO_COPYRIGHT:
        i_start, i_end = result
        lines = lines[:i_start] + lines[i_end + 1:]

    # add new copyright at top of file
    if not opts.strip_copyright:

        # strip empty leading lines
        while lines and not lines[0]:
            lines = lines[1:]

        copyright_lines = new_copyright.strip().split('\n')
        lines = copyright_lines + ['', ''] + lines

    # strip empty leading lines
    while lines and not lines[0]:
        lines = lines[1:]

    # strip trailing empty lines
    while lines and not lines[-1]:
        lines = lines[:-1]

    # output
    new_txt = '\n'.join(lines) + '\n'

    if not opts.overwrite_file:
        print(new_txt)
    elif new_txt == txt:
        if not IN_WORKFLOW:
            print("(file contents unchanged)")
    else:
        with open(opts.FILE, 'w') as f:
            f.write(new_txt)

        print("Replaced %s" % opts.FILE, file=sys.stderr)
